package com.sp.service;

import com.sp.pojo.SpReePlatform;
import com.sp.mapper.SpReePlatformMapper;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.sp.result.Pager;
import com.sp.result.Result;
import com.sp.result.Parameter;
import com.sp.result.ParameterUtil;
import java.util.*;
import java.util.List;
import com.sp.util.PoiExport;
import com.sp.util.Tool;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import com.sp.util.PoiReadUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.PrintWriter;
import org.springframework.web.multipart.MultipartFile;

import org.apache.commons.lang3.StringUtils;
import javax.annotation.Resource;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import javax.servlet.http.HttpServletResponse;

@Service
public class SpReePlatformServiceImpl implements SpReePlatformService{

@Resource
private SpReePlatformMapper spReePlatformMapper;
@Resource
private HttpServletResponse response;
/**
*增加数据
**/
public  int insertSpReePlatform(SpReePlatform record)throws Exception{
int totalRecords=0;

    totalRecords+=spReePlatformMapper.insert(record);

return totalRecords;
}

    /**
    *删除数据
    **/
    public  int deleteSpReePlatformByPrimaryKey( Integer spReePlatformId )throws Exception{
    int totalRecords=0;
        totalRecords+= spReePlatformMapper.deleteById(  spReePlatformId );


    return totalRecords;

    }

    /**
    * 通过主键删除多条数据
    **/
    public int deleteSpReePlatformByIds( String [] spReePlatformIds )throws Exception{
    int totalRecords=0;
        totalRecords+= spReePlatformMapper.deleteBatchIds(     Arrays.asList( spReePlatformIds) );
   return totalRecords;


    }


    /**
    * 更新数据
    **/
    public  int updateSpReePlatformByPrimaryKey(SpReePlatform record)throws Exception{
    int totalRecords = 0;
        totalRecords += spReePlatformMapper.updateById(record);

    return totalRecords;

    }
    /**
    * 批量更新属性不为空数据
    **/
    public  int updateSpReePlatformByPrimaryKeyNotNull(SpReePlatform record, String[] spReePlatformIds) throws Exception{
    int totalRecords = 0;
        if(spReePlatformIds==null || spReePlatformIds.length<0){
        if(record.getSpReePlatformId()!=null){
        spReePlatformIds=new String[]{String.valueOf(record.getSpReePlatformId())};
        }
        }
        if(spReePlatformIds!=null || spReePlatformIds.length>0) {

        for (String spReePlatformId:spReePlatformIds){
        record.setSpReePlatformId(Integer.valueOf(spReePlatformId));

            totalRecords += spReePlatformMapper.updateById(record);


        }
        }

    return totalRecords;

    }

    /**
    * 通过主键查询数据
    **/
    public  SpReePlatform selectSpReePlatformByPrimaryKey( Integer spReePlatformId ){

        SpReePlatform data=  spReePlatformMapper.selectById(  spReePlatformId );
     return data;
    }


/**
* 通过条件查询数据
**/
public List<SpReePlatform> selectSpReePlatform(SpReePlatform spReePlatform, String desc, String startTime, String endTime, String notNullAttributes,
String isNullAttributes, String globalSearch,String likeNameSearch, Double amountSearch, String universalTime,String multipleChoiceCondition, String fieldConditionStr){
    Parameter<SpReePlatform> parameter = new Parameter<>();


    parameter.setData(spReePlatform);
    parameter.setDesc(desc);

    parameter.setStartTime(startTime);
    parameter.setEndTime(endTime);
    parameter.setAmountSearch(amountSearch);
    ParameterUtil parameterUtil = new ParameterUtil();
    parameterUtil.notNullAttributes = notNullAttributes;
    parameterUtil.isNullAttributes = isNullAttributes;
    parameterUtil.globalSearch = globalSearch;
    parameterUtil.likeNameSearch = likeNameSearch;
    parameterUtil.amountSearch = amountSearch;
    parameterUtil.multipleChoiceCondition = multipleChoiceCondition;
    parameterUtil.universalTime = universalTime;
    parameterUtil.fieldConditionStr = fieldConditionStr;
    parameterUtil.setParameterValue(parameter);

    List<SpReePlatform> list =spReePlatformMapper.selectSpReePlatform(parameter);
    return list;
}

/**
*总条数
**/
public long getSpReePlatformPageCount(SpReePlatform spReePlatform, String desc, String startTime,
String endTime, String notNullAttributes,
String isNullAttributes, String globalSearch,String likeNameSearch, Double amountSearch, String universalTime,String multipleChoiceCondition, String fieldConditionStr){
    Parameter<SpReePlatform> parameter = new Parameter<>();


    parameter.setData(spReePlatform);
    parameter.setDesc(desc);

    parameter.setStartTime(startTime);
    parameter.setEndTime(endTime);
    parameter.setAmountSearch(amountSearch);
    ParameterUtil parameterUtil = new ParameterUtil();
    parameterUtil.notNullAttributes = notNullAttributes;
    parameterUtil.isNullAttributes = isNullAttributes;
    parameterUtil.globalSearch = globalSearch;
    parameterUtil.likeNameSearch = likeNameSearch;
    parameterUtil.amountSearch = amountSearch;
    parameterUtil.multipleChoiceCondition = multipleChoiceCondition;
    parameterUtil.universalTime = universalTime;
    parameterUtil.fieldConditionStr = fieldConditionStr;
    parameterUtil.setParameterValue(parameter);
    long l =spReePlatformMapper.getSpReePlatformPageCount(parameter);
    return l;


}
/**
* 分页条件查询
**/
public Pager<SpReePlatform> getSpReePlatformPage(long curPage, int pageSize, String
orderBy, SpReePlatform spReePlatform, String desc, String startTime, String endTime, String
notNullAttributes,
String isNullAttributes, String globalSearch,String likeNameSearch, Double amountSearch, String universalTime,String multipleChoiceCondition, String fieldConditionStr,String isLimit){
    Parameter<SpReePlatform> parameter = new Parameter<>();

    parameter.setOrderBy(orderBy);
    parameter.setData(spReePlatform);
    parameter.setDesc(desc);
    parameter.setPageSize(pageSize);
    parameter.setStartTime(startTime);
    parameter.setEndTime(endTime);
    parameter.setIsLimit(isLimit);
    parameter.setAmountSearch(amountSearch);
    ParameterUtil parameterUtil = new ParameterUtil();
    parameterUtil.notNullAttributes = notNullAttributes;
    parameterUtil.isNullAttributes = isNullAttributes;
    parameterUtil.globalSearch = globalSearch;
    parameterUtil.likeNameSearch = likeNameSearch;
    parameterUtil.amountSearch = amountSearch;
    parameterUtil.multipleChoiceCondition = multipleChoiceCondition;
    parameterUtil.universalTime = universalTime;
    parameterUtil.fieldConditionStr = fieldConditionStr;
    parameterUtil.setParameterValue(parameter);

    Pager<SpReePlatform>   pager =null;
    if(!StrUtil.isEmpty(isLimit)&&isLimit.equals("false")){
        pager = new Pager(0, pageSize, curPage);
        pager.setCode(0);
        pager.setMsg("查询成功");
        List<SpReePlatform> list = spReePlatformMapper.getSpReePlatformPage(parameter);
        pager.setDatas(list);
     }else{
            long totalRecords =spReePlatformMapper.getSpReePlatformPageCount(parameter);
            pager = new Pager(totalRecords, pageSize, curPage);
            pager.setCode(0);
            pager.setMsg("查询成功");
            if (totalRecords > 0) {
            parameter.setStartIndex(pager.getStartIndex());
            parameter.setEndIndex(pager.getEndIndex());
            List<SpReePlatform> list = spReePlatformMapper.getSpReePlatformPage(parameter);
            pager.setDatas(list);
        }
    }




    return pager;
}
    /**
    * 导出表格中字段
    * @param attributeMap
    */
    public void setAttributeMap(LinkedHashMap<String, String> attributeMap) {



                attributeMap.put("交易平台名称", "spReePlatformName");


                attributeMap.put("字段", "spReeTemplateStr");


                attributeMap.put("表头行位置", "spReeTemplateTitleRowIndex");




    }

    /**
    * 导出模板
    *
    * @throws Exception
    */
    @Override
    public void exportSpSupplierTemplate() throws Exception {
        LinkedHashMap<String, String> attributeMap = new LinkedHashMap<>();
        setAttributeMap(attributeMap);



        Map<String, String[]> dropDownBoxAttributeMap = new HashMap<>();



        HSSFWorkbook workbook = PoiExport.createWorkbookTitleRow("信息", "信息", attributeMap, dropDownBoxAttributeMap, null);

        PoiExport.responseFile(workbook, response, "模板.xlsx");
    }


    /**
    * 导出供应商
    * @param orderBy 以什么排序
    * @param spReePlatform
    * @param desc 是否降序排序
    * @param startTime 开始时间
    * @param endTime 结束时间
    * @param notNullAttributes 不为空筛选  多个,分割
    * @param isNullAttributes 为空筛选 多个
    * @param globalSearch
    * @param likeNameSearch 模糊查询 格式 {字段:'条件'}
    * @param amountSearch 数值模糊查询
    * @param universalTime 时间 格式 {字段:{startTime:'',endTime:''}}
    * @param multipleChoiceCondition 多选条件格式 {字段:[数据,数据]}
    * @param fieldConditionStr 高级查询json 格式[{databaseId:'',relationId:'',datas:[]}]
    * @throws Exception
    */
    @Override
    public void exportSpSupplier(String orderBy, SpReePlatform spReePlatform, String desc, String startTime, String endTime, String notNullAttributes, String isNullAttributes, String globalSearch, String likeNameSearch, Double amountSearch, String universalTime, String multipleChoiceCondition, String fieldConditionStr) throws Exception {
    Parameter<SpReePlatform> parameter = new Parameter<>();

        parameter.setOrderBy(orderBy);
        parameter.setData(spReePlatform);
        parameter.setDesc(desc);
        parameter.setIsLimit("false");
        parameter.setStartTime(startTime);
        parameter.setEndTime(endTime);
        parameter.setAmountSearch(amountSearch);
        ParameterUtil parameterUtil = new ParameterUtil();
        parameterUtil.notNullAttributes = notNullAttributes;
        parameterUtil.isNullAttributes = isNullAttributes;
        parameterUtil.globalSearch = globalSearch;
        parameterUtil.likeNameSearch = likeNameSearch;
        parameterUtil.amountSearch = amountSearch;
        parameterUtil.multipleChoiceCondition = multipleChoiceCondition;
        parameterUtil.universalTime = universalTime;
        parameterUtil.fieldConditionStr = fieldConditionStr;
        parameterUtil.setParameterValue(parameter);

        List<SpReePlatform> list = spReePlatformMapper.getSpReePlatformPage(parameter);


            LinkedHashMap<String, String> attributesMap = new LinkedHashMap<>();
                attributesMap.put("交易平台编号", "spReePlatformId");

            setAttributeMap(attributesMap);

            Set<String> attributeKeys = attributesMap.keySet();
                List<String> attributeKeyList = new ArrayList<>(attributeKeys);




                    Map<String, String[]> dropDownBoxAttributeMap = new HashMap<>();


                    String sheetName = "信息";
                    HSSFWorkbook workbook = PoiExport.createWorkbookTitleRow(sheetName, "信息", attributesMap, dropDownBoxAttributeMap, null);
                    HSSFSheet sheet = workbook.getSheet(sheetName);


                    HSSFCellStyle strStyle = PoiExport.strStyle(workbook, null);
                    HSSFCellStyle strStyle2 = PoiExport.strStyle2(workbook, null);
                    HSSFCellStyle datestyle = PoiExport.Datestyle(workbook, null);
                    HSSFFont firstFont = workbook.createFont();
                    firstFont.setFontName("宋体");
                    firstFont.setFontHeightInPoints((short) 11);
                    firstFont.setColor(IndexedColors.RED.getIndex());
                    firstFont.setBold(true);
                    HSSFCellStyle firstCellStyle = PoiExport.firstCellStyle(workbook, firstFont);
                    HSSFFont hjFont = workbook.createFont();
                    hjFont.setFontName("宋体");
                    hjFont.setFontHeightInPoints((short) 11);
                    HSSFCellStyle hjCellStyle = workbook.createCellStyle();
                    hjCellStyle.setBorderBottom(BorderStyle.THIN);
                    hjCellStyle.setBorderRight(BorderStyle.THIN);
                    hjCellStyle.setAlignment(HorizontalAlignment.CENTER);
                    hjCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                    hjCellStyle.setWrapText(true);
                    hjCellStyle.setDataFormat(workbook.createDataFormat().getFormat("#,##0.00"));
                    hjCellStyle.setFillForegroundColor(IndexedColors.PINK.getIndex());
                    hjCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                    hjCellStyle.setFont(hjFont);
                    HSSFCellStyle BigDecimalstyle = PoiExport.BigDecimalstyle(workbook);
                    Map<String, HSSFCellStyle> cellStyleMap = new HashMap<>();
                    cellStyleMap.put("String", strStyle);
                    cellStyleMap.put("BigDecimal", BigDecimalstyle);
                    cellStyleMap.put("Date", datestyle);

                    int lastRow = sheet.getLastRowNum();
                    for (SpReePlatform data : list) {


                        lastRow += 1;
                        HSSFRow rowData = sheet.createRow(lastRow);
                        for (int i = 0; i < attributeKeyList.size(); i++) {
                        String attributeKeyName = attributeKeyList.get(i);
                        String fieldName = attributesMap.get(attributeKeyName);
                        HSSFCell cell = rowData.createCell(i);
                        Object value = null;


                        value = Tool.getFieldByClass(fieldName, data);



                        PoiExport.setCellValue(cell, value, cellStyleMap);
                    }


                    }

                    PoiExport.responseFile(workbook, response);


                    }

    /**
    * 导入供应商数据
    *
    * @param file
    * @throws Exception
    */
    @Override
    public void importSpReePlatform(MultipartFile file) throws Exception {
        LinkedHashMap<String, String> attributesMap = new LinkedHashMap<>();
            attributesMap.put("交易平台编号", "spReePlatformId");
        setAttributeMap(attributesMap);
        Set<String> attributeKeys = attributesMap.keySet();
            List<String> attributeKeyList = new ArrayList<>(attributeKeys);

                Map<String, String> reverse = MapUtil.reverse(attributesMap);


                List<String> specialHandlingFields = new ArrayList<>();//需要特殊处理字段


                    List<String> canBeEmptyFields = new ArrayList<>();// 跳过判空


                        canBeEmptyFields.add("spReePlatformId");




                        Workbook workBook = null;
                        PoiReadUtil<SpReePlatform> poiReadUtil = new PoiReadUtil();
                            workBook = poiReadUtil.readWorkbookData(workBook, file, attributesMap, specialHandlingFields, canBeEmptyFields, SpReePlatform.class);
                            CellStyle cellStyleBk = PoiExport.strStyleRed(workBook, null);
                            CellStyle strStyleBrown = PoiExport.strStyleBrown(workBook, null);

                            List<PoiReadUtil<SpReePlatform>.PoiReadData> poiReadDataList = poiReadUtil.getPoiReadDataList();
                                int numberOfFailures = poiReadUtil.getNumberOfFailures();//失败行数
                                int totalRecords = 0;
                                for (PoiReadUtil<SpReePlatform>.PoiReadData data : poiReadDataList) {
                                    try {
                                    boolean isSuccess = true;
                                    SpReePlatform  spReePlatform = data.getModelData();

                                    LinkedHashMap<String, Map<String, String>> attributesMapI = data.getAttributesMapI();//所有表头位置
                                    LinkedHashMap<String, Map<String, String>> attributesMapL = data.getAttributesMapL();//所有表头位置

                                    int rowIndex = data.getRowIndex();//数据在表格中行
                                    int sheetIndex = data.getSheetIndex();//第几个工作表
                                    Sheet sheet = workBook.getSheetAt(sheetIndex);
                                    Row row = sheet.getRow(rowIndex);
                                    Map<String, Object> specialHandlingFieldMap = data.getSpecialHandlingFieldMap();//需要特殊处理的字段及值
                                    if (specialHandlingFieldMap != null && specialHandlingFieldMap.size() > 0) {
                                    Set<String> specialHandlingFieldKey = specialHandlingFieldMap.keySet();


                                        for (String key : specialHandlingFieldKey) {
                                        Object value = specialHandlingFieldMap.get(key);
                                        if (value == null) continue;
                                        String attributeName = reverse.get(key);

                                        Map<String, String> map = attributesMapL.get(attributeName);
                                        String index = map.get("index");
                                        Cell cell = row.getCell(Integer.parseInt(index));

                                        String s = value.toString().trim();
                                        try {


                                        } catch (Exception e) {
                                        e.printStackTrace();
                                        numberOfFailures += 1;
                                        isSuccess = false;

                                        if (cell == null) {
                                        cell = row.createCell(Integer.parseInt(index));
                                        }
                                        cell.setCellStyle(cellStyleBk);
                                        continue;
                                        }


                                        }
                                        }

                                        if (spReePlatform == null || !isSuccess) {
                                        numberOfFailures += 1;
                                        continue;

                                        }




                                            Integer spReePlatformId = spReePlatform.getSpReePlatformId();

                                        if (
                                                
                                                                                                    spReePlatformId !=null



                                                ) {

                        totalRecords += spReePlatformMapper.updateById(spReePlatform);

                                        } else {

                                        totalRecords += insertSpReePlatform(spReePlatform);

                                        sheet.removeRow(row);


                                        }
                                        } catch (Exception e) {
                                        e.printStackTrace();
                                        numberOfFailures += 1;
                                        }


                                        }
                                        PrintWriter out = null;
                                        try {
                                        PoiExport.importReturn(numberOfFailures, response, workBook, out, totalRecords);
                                        } catch (Exception e) {
                                        e.printStackTrace();
                                        } finally {
                                        if (out != null) {
                                        out.close();
                                        }
                                        if (workBook != null) {
                                        workBook.close();
                                        }
                                        }
                                    }

}